# app/api/routes/computer_rooms.py
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from typing import List

from app.core.database import get_db
from app.schemas import schemas
from app.crud import crud
from app.api.routes.auth import get_current_user
from fastapi.exceptions import HTTPException

router = APIRouter()


@router.get("/", response_model=List[schemas.ComputerRoom])
def read_computer_rooms(
    skip: int = 0,
    limit: int = 100,
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user),
):
    return crud.get_computer_rooms(db, skip=skip, limit=limit)


@router.get("/{room_id}", response_model=schemas.ComputerRoom)
def read_computer_room(
    room_id: int,
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user),
):
    db_room = crud.get_computer_room(db, room_id=room_id)
    if db_room is None:
        raise HTTPException(status_code=404, detail="机房不存在")
    return db_room


@router.post("/", response_model=schemas.ComputerRoom)
def create_computer_room(
    room: schemas.ComputerRoomCreate,
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user),
):
    return crud.create_computer_room(db=db, room=room)


@router.patch("/{room_id}/rate")
def update_computer_room_rate(
    room_id: int,
    hourly_rate: float,
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user),
):
    result = crud.update_computer_room_rate(db=db, room_id=room_id, rate=hourly_rate)
    if result:
        return {"message": "更新成功"}
    else:
        raise HTTPException(status_code=400, detail="更新失败")


@router.patch("/{room_id}/status")
def update_computer_room_status(
    room_id: int,
    status: str,
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user),
):
    result = crud.update_computer_room_status(db=db, room_id=room_id, status=status)
    if result:
        return {"status": "successful", "message": "更新成功"}
    raise HTTPException(status_code=400, detail="更新失败")

@router.delete("/{room_id}")
def delete_computer_room(
    room_id: int,
    db: Session = Depends(get_db),
    current_user=Depends(get_current_user),
):
    result = crud.delete_computer_room(db=db, room_id=room_id)
    if result is None:
        raise HTTPException(status_code=404, detail="机房不存在")
    return {"status": "successful", "message": "删除机房成功"}